package com.lkdont.cameratest

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.lkdont.android.base.ui.BaseFrag
import com.lkdont.android.media.examples.R

private const val PERMISSIONS_REQUEST_CODE = 10
private val PERMISSIONS = arrayOf(Manifest.permission.CAMERA)

/**
 * 检查权限Fragment，如果没有权限则弹出权限对话框；如果已经有权限则自动进入下一个页面。
 *
 * @author lqd
 */
class PermissionsFrag : BaseFrag() {

    companion object {
        private val TAG = PermissionsFrag::class.java.simpleName
    }

    private val navController: NavController by lazy {
        Navigation.findNavController(requireActivity(), R.id.nav_host_fragment)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (hasPermissions(PERMISSIONS)) {
            // 进入拍照界面
            Log.d(TAG, "onCreate: hasPermissions(PERMISSIONS)")
            navController.navigate(PermissionsFragDirections.actionPermissionsFragToExampleListFrag())
        } else {
            Log.w(TAG, "onCreate: no PERMISSIONS")
            requestPermissions(PERMISSIONS, PERMISSIONS_REQUEST_CODE)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 进入拍照界面
                navController.navigate(PermissionsFragDirections.actionPermissionsFragToExampleListFrag())
            } else {
                showMessage("No Permissions!")
            }
        }
    }
}